import moment from "moment";

const Message = function (obj) {
    this._init_(obj);
};

Message.prototype = {
    constructor: Message,
    _init_: function (obj) {
        if (obj) {
            this.messageId = obj.messageId == undefined ? null : obj.messageId;
            this.messageContent = obj.messageContent
            this.messageDirection = obj.messageDirection; //C:顾客发给机器人, U机器人发给顾客，S系统
            this.messageType = obj.messageType; //信息类型  // T:文本 I:图片 V:视频 F:文件 S1:系统消息(发送给顾客) S2:系统消息(发送给客服) R:机器人回复消息
            this.sendTime = obj.sendTime;//发送时间
            this.messageStatus = obj.messageStatus;//-1:发送失败0:发送中10:未读 20:已读 30:离线:40撤回
            this.sessionId = obj.sessionId == undefined ? null : obj.sessionId;//-1:发送失败0:发送中10:未读 20:已读 30:离线:40撤回
            this.solveStatus = typeof obj.solveStatus != 'undefined' && obj.solveStatus ? obj.solveStatus : typeof obj.resolveFlag != 'undefined' && obj.resolveFlag ? obj.resolveFlag+1 : "1"; //未提交,2已解决3,未解决
            this.chatId = obj.chatId;
            this.showResolveStatusLabel = typeof obj.showResolveStatusLabel != 'undefined' ? obj.showResolveStatusLabel : null;

            // 前端辅助字段
            this.retryCount = obj.retryCount;
            this.successCallback = obj.successCallback;// 消息发送成功回调函数
            this.failCallback = obj.failCallback;// 消息发送失败回调函数
            this.readCallback = obj.readCallback;// 消息被接收方已读回调函数
            this.sendFileStatus = obj.sendFileStatus == undefined ? 1 : obj.sendFileStatus;//0:上传中,1:上传成功，2:上传失败
            this.isOpen = false;//是否展开
            this.isHasOpen = false;//是否有展开按钮
            this.heightOfMobile = '275px';//移动端高度
            this.heightOfPC = 'unset';//pc端高度
        }
    },

    showType: function () {
        var _this = this;
        if (_this.messageType == 'R' && _this.isJSON(_this.messageContent)) {
            var data = JSON.parse(_this.messageContent);
            if (data.choices.length > 0 || data.suggestions.length > 0) { // 有选项消息
                return true;
            }
        };
        return false;

        // var _this = this;
        // if (_this.messageType == 'R' && _this.isJSON(_this.messageContent)) {
        //     var data = JSON.parse(_this.messageContent);
        //     if (data.choices.length > 0 || data.suggestions.length > 0) {
        //         // 有选项消息
        //         return true;
        //     }
        // }
        // if (_this.messageType == 'Z' && JSON.parse(_this.messageContent).length > 0) {
        //     return true;
        // }
        // if (_this.messageType == 'I' || _this.messageType == 'V' || _this.messageType == 'F') {
        //     return true;
        // }
        // return false;
    },
    getHtml: function () {
        var _this = this;
        var content = JSON.parse(JSON.stringify(_this.messageContent));
        if (_this.isJSON(content)) {
            content = JSON.parse(content).answer;
            if (content == '#转人工#') {
                content = '抱歉，暂不支持人工客服'
            }
        };
        var regexList = [];
        regexList.push({ regex: /<a(.*?)target='[^']*'(.*?)>/ig, value: "<a$1target='_blank '$2>" });
        regexList.push({ regex: /<a(((?!target).)*?)>/ig, value: "<a target='_blank '$1>" });

        //获取机器人消息体整体宽度
        let contentDivWidth = document.querySelector('.contentDiv').clientWidth * 0.75;

        regexList.push({ regex: /<img(.*?)onclick='[^']*'(.*?)>/ig, value: "<img $1 onclick='openRobotLinkEvent(this,\"" + "img" + "\") '$2>" });
        regexList.push({ regex: /<img(((?!onclick).)*?)>/ig, value: "<img onclick='openRobotLinkEvent(this,\"" + "img" + "\") '$1>" });
        regexList.push({ regex: /<video(.*?)controls='[^']*'(.*?)>/ig, value: "<video$1 controls $2>" });
        regexList.push({ regex: /<video(((?!controls).)*?)>/ig, value: "<video controls $1>" });
        regexList.push({ regex: /<video(.*?)preload="[^"]*'(.*?)>/ig, value: "<video$1 preload='preload' $2>" });
        regexList.push({ regex: /<video(((?!preload).)*?)>/ig, value: "<video preload='preload' $1>" });
        regexList.push({ regex: /<video(.*?)autoplay='[^']*'(.*?)>/ig, value: "<video$1 $2>" });
        regexList.push({ regex: /<video(.*?)autoplay(.*?)>/ig, value: "<video$1 $2>" });
        /**
         * 控制宽高
         */
        const videoContentWidth = content.match(/<video(.*?)width="[^"]*"(.*?)>/ig);
        const videoContentHeight = content.match(/<video(.*?)height="[^"]*"(.*?)>/ig);
        let videoWidth = null;
        let videoHeight = null;
        //获取video的宽高
        const videoEleWidth = videoContentWidth ? videoContentWidth[0].match(/width="[^"]*"/ig) : null;
        const videoEleHeight = videoContentHeight ? videoContentHeight[0].match(/height="[^"]*"/ig) : null;
        if (videoEleWidth && videoEleWidth[0]) {
            videoWidth = videoEleWidth[0].match(/"[^"]*"/ig)[0].split("\"")[1];
        };
        if (videoEleHeight && videoEleHeight[0]) {
            videoHeight = videoEleHeight[0].match(/"[^"]*"/ig)[0].split("\"")[1];
        };
        //判断video的宽和气泡的最大宽 若video大于气泡 则取气泡的宽 高等比例展示  若video小于气泡 则取video本身宽高
        if (videoWidth && videoWidth > contentDivWidth) {
            console.log('气泡宽=====' + contentDivWidth + '\n' + 'video宽=======' + videoWidth + '\n' + 'video高=======' + videoHeight)
            const actualHeight = videoHeight * (contentDivWidth / videoWidth);
            regexList.push({ regex: /<video(.*?)width="[^"]*"(.*?)>/ig, value: "<video$1 width='" + contentDivWidth + "' $2>" })
            regexList.push({ regex: /<video(.*?)height="[^"]*"(.*?)>/ig, value: "<video$1 height='" + actualHeight + "' $2>" })
        };
        for (var i = 0; i < regexList.length; i++) {
            content = content.replace(regexList[i].regex, regexList[i].value);
        };
        if (_this.isJSON(content)) {
            let jsonForContent = JSON.parse(content);
            if (jsonForContent.templateOp !== undefined) {
                // return this.dealWithContent(jsonForContent)
                console.log(jsonForContent)
                return jsonForContent
            }
        };
        return content;
    },
    is_weiXin: function () {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        } else {
            return false;
        }
    },
    getSystemHtml: function (sessionIdNow) {
        var keyWordList = [];
        var messageContent = this.messageContent
        if (messageContent.indexOf('#重新接入#') > -1) {
            keyWordList.push('#重新接入#')
        };
        for (var i = 0; i < keyWordList.length; i++) {
            if (keyWordList[i] == '#重新接入#') {
                if (sessionIdNow == null) {
                    var keyHtml = '<a onclick="initClickEvent(\'' + keyWordList[i] + '\')" style="color: #ffffff; background: #FFB63D; padding: 2px 5px; cursor: pointer; border-radius: 25px; white-space: nowrap;">' + keyWordList[i] + '</a>';
                    messageContent = messageContent.replace(keyWordList[i], keyHtml);
                }
            }
        };
        return messageContent;
    },
    getSendTime: function () {
        // return moment(this.sendTime*1).format('MM-DD HH:mm:ss');
        return moment(this.sendTime * 1).format('MM-DD HH:mm:ss');
    },
    isJSON: function (str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                return false;
            }
        };
        return false;
    },
    toString: function () {
        return JSON.stringify(this);
    },
};
export default Message;
